//
//  PhotoCropManager.m
//  AncientVillage
//
//  Created by 陈志亮 on 2018/9/14.
//  Copyright © 2018年 LSJ. All rights reserved.
//

#import "PhotoCropManager.h"
#import "PhotoAlertViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "ShowMessageViewController.h"
#import "ChatHandleCommonLogic.h"



@interface PhotoCropManager ()
@property(nonatomic,strong)ShowMessageViewController*showVC;
@end


@implementation PhotoCropManager
static PhotoCropManager*manager = nil;

+(PhotoCropManager*)photoCropSharedManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [self new];
    });
    return manager;
}


-(void)showHintView:(UIViewController*)inViewController scale:(CGFloat)cropScale isAvater:(BOOL)isAvater  andResultBlock:(resultURLBlock)imgBlcok{

    self.baseVC=(DSBaseViewController*)inViewController;
    self.resultBlock =imgBlcok;
    self.isUploadAvater=isAvater;
   
    
    UIAlertController * alerController = [PhotoAlertViewController getPhotoAlbumAlertLeftBlock:^(UIAlertAction *  action) {
        [self takePhoto];
    } rightBlock:^(UIAlertAction *  action) {
        [self chosePhotoFromAsset:NO];
    }];
    alerController.modalPresentationStyle =UIModalPresentationFullScreen;
    [self.baseVC presentViewController:alerController animated:YES completion:nil];
}

#pragma mark----公共方法
//拍照
-(void)takePhoto{
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
         [self gotoSetOpenPhotoAuth];//去设置页面打开相机权限

    }else
    {
      
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            [[UIApplication sharedApplication].keyWindow endEditing:YES];
            //初始化照相机对象
            UIImagePickerController *imagePC = [[UIImagePickerController alloc] init];
            imagePC.delegate = self;
            imagePC.sourceType = UIImagePickerControllerSourceTypeCamera;
            imagePC.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self.baseVC presentViewController:imagePC animated:YES completion:nil];
        }
        else
        {
    
            UIAlertController * alertView = [PhotoAlertViewController getAlertViewWithTitle:@"您当前的摄像头不可用" cancleTitle:@"好的" cancleBlock:nil];
             alertView.modalPresentationStyle =UIModalPresentationFullScreen;
             [self.baseVC presentViewController:alertView animated:YES completion:nil];
        }
        
    }
    
}
// 系统拍照代理（备注:此方法是系统拍照用）
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
 
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    //保存图片至相册
   UIImageWriteToSavedPhotosAlbum(image,self,@selector(image:didFinishSavingWithError:contextInfo:), NULL);
    image = [UIImage jk_fixOrientation:image];
   
   [self.baseVC dismissViewControllerAnimated:NO completion:^{
        if(@available(iOS 11.0,*)){
            UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }];
}
- (void)image:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInf{
    if (error) {
        NSLog(@"保存过程中发生错误，错误信息:%@",error.localizedDescription);
    }else{
        NSLog(@"保存成功.");
    }
}

//从相册选择
-(void)chosePhotoFromAsset:(BOOL)isCrop{

    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted ||
        status == PHAuthorizationStatusDenied) {
        [self gotoSetOpenPhotoAuth];
    }else
    {
        TZImagePickerController * pickerVC = [[TZImagePickerController alloc]initWithMaxImagesCount:1  delegate:self];
        pickerVC.allowTakePicture=YES;
        pickerVC.allowPickingVideo=NO;
        if (isCrop) {
            pickerVC.allowCrop=isCrop;
            //设置裁剪比例
            CGFloat rate =0.8;
            CGFloat cropWidth = adaptWidth750(363*rate*2);
            CGFloat cropHeight =adaptWidth750(608*rate*2);
            pickerVC.cropRect = CGRectMake((IMSCREEN_WIDTH - cropWidth) / 2, (IMSCREEN_HEIGHT - cropHeight) / 2, cropWidth, cropHeight);
        }
        pickerVC.modalPresentationStyle =UIModalPresentationFullScreen;
        [self.baseVC presentViewController:pickerVC animated:YES completion:nil];
    }
}
//tzimg代理（备注:此方法是选择照片用）
-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos{
    PHAsset * asset = assets[0];
    if(asset.mediaType==PHAssetMediaTypeImage){
     
        [[TZImageManager manager] getPhotoWithAsset:asset completion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
            if(!isDegraded)//这个回调会调用2次，缩略图和原图，去掉缩略图
            {
                !self.resultBlock?:self.resultBlock(@"",photo);
            }
        }];
    }
}
//跳转设置页面打开相册权限
-(void)gotoSetOpenPhotoAuth{
    WS(weakSelf);
    ShowMessageViewController *showVC = [[ShowMessageViewController alloc]initWithArr:@[@"取消",@"去设置"]];
    showVC.messageLabel.text=@"请在iPhone的""设置-隐私-相机""中允许访问";
    showVC.ensureBlock = ^{
        [weakSelf.showVC dismissFromParentVC];
        [[ChatHandleCommonLogic new]jumpSystemSetting];
    };
    
    showVC.cancleBlock = ^{
        [weakSelf.showVC dismissFromParentVC];
    };
    
    [showVC showCurrentVC:self.baseVC.navigationController];
    
}


@end
